package service;

import java.util.ArrayList;
import java.util.Iterator;

import domain.User;

public class UserHolder {

	private ArrayList<User> loggedInUsers;
	private static UserHolder instance;
	private static final Object singletonObject = new Object();
	
	private UserHolder() {
		loggedInUsers = new ArrayList<User>();
	}


	public static UserHolder getInstance() {
		if(instance == null) {
			synchronized(singletonObject) {
				if(instance == null) {
					instance = new UserHolder();
				}
			}
		}
		
		return instance;
	}

	public boolean contains(User user) {
		boolean bool = false;
		synchronized(this) {
			bool = loggedInUsers.contains(user);
		}
		return bool;
	}
	
	public User getUser(String user){
		User result = null;
		synchronized (this) {
			for (int i = 0; i < loggedInUsers.size(); i++) {
				if(user.equals(loggedInUsers.get(i).getName())){
					System.out.println(loggedInUsers.get(i).getName());
					result = loggedInUsers.get(i);
					break;
				}
			}
		}
		
		
		return result;
	}
	
	public int howOftenGroupBid(String str){
		int x = 0;
		
		synchronized (this) {
			for (int i = 0; i < loggedInUsers.size(); i++) {
				if(str.equals(loggedInUsers.get(i).getName())){
					x = loggedInUsers.get(i).getGroupbidden();
				}
			}
		}
		
		return x;
	}
	
	public void setGroupBidden(String str){
		for (int i = 0; i < loggedInUsers.size(); i++) {
			if(loggedInUsers.get(i).getName().equals(str)){
				loggedInUsers.get(i).setGroupbidden(loggedInUsers.get(i).getGroupbidden()+1);
			}
		}
	}
	
	public void setToZeroGroupBidden(String str){
		for (int i = 0; i < loggedInUsers.size(); i++) {
			if(loggedInUsers.get(i).getName().equals(str)){
				loggedInUsers.get(i).setGroupbidden(0);
			}
		}
	}
	
	

	public void add(User user) {
		synchronized(this) {
			loggedInUsers.add(user);
		}
	}

	public void remove(User user) {
		synchronized(this) {
			loggedInUsers.remove(user);
		}
	}
	
	public int getNumberLoggedInUsers() {
		return loggedInUsers.size();
	}


	/**
	 * @return the loggedInUsers
	 */
	public Iterator<User> getLoggedInUsers() {
		return loggedInUsers.iterator();
	}
	
	

}
